package com.hr.异步调用;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: leetcode
 * @description: 公平
 * @author: HuRan QQ1345122890
 * @create: 2021-08-17 10:46
 */
public class ReentrantLockTest03 {

    public static void main(String[] args) throws InterruptedException {

        WaitNotify2 waitNotify2 = new WaitNotify2(5);
        final Condition a = waitNotify2.newCondition();
        final Condition b = waitNotify2.newCondition();
        final Condition c = waitNotify2.newCondition();
        new Thread(new Runnable() {
            @Override
            public void run() {
                waitNotify2.print("a", a, b);
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                waitNotify2.print("b", b, c);
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                waitNotify2.print("c", c, a);
            }
        }).start();
        Thread.sleep(2000);
        waitNotify2.lock();
        a.signalAll();
        waitNotify2.unlock();


    }
}

class WaitNotify2 extends ReentrantLock {

    private int count;

    public WaitNotify2(int count) {
        this.count = count;
    }

    public void print(String str, Condition curr, Condition next) {
        for (int i = 0; i < count; i++) {
            lock();
            try {
                curr.await();
                System.out.println(str);
                next.signalAll();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                unlock();
            }
        }
    }
}

class ParkUnpark {
    public void print(String str, Thread next) {
        for (int i = 0; i < 5; i++) {
            LockSupport.park(this);
            System.out.println(str);
            LockSupport.unpark(next);
        }
    }
}